import Tile from "../component/Tile";

const {ccclass, property} = cc._decorator;

/**
 * 管理游戏中频繁用到的预制体
 */
@ccclass
export default class PoolManager extends cc.Component {

    @property(cc.Prefab)
    private tilePrefab: cc.Prefab = null;
    private tilePool: cc.NodePool = new cc.NodePool(Tile);
    private static instance: PoolManager = null;

    onLoad () {
        PoolManager.instance = this;
    }

    /**
     * 获取节点
     */
    public static get(): cc.Node {
        let tileNode = null;
        if (PoolManager.instance.tilePool.size() > 0) {
            tileNode = PoolManager.instance.tilePool.get();
        } else {
            tileNode = cc.instantiate(PoolManager.instance.tilePrefab);
        }
        return tileNode;
    }

    /**
     * 存入节点
     * @param node
     */
    public static put(node: cc.Node) {
        cc.Tween.stopAllByTarget(node);
        // 节点池的节点维持在30个
        if (PoolManager.instance.tilePool.size() > 30) {
            node.destroy();
        } else {
            PoolManager.instance.tilePool.put(node);
        }
    }
}
